package com.cvmars.jianyou.module.fragment;

import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.config.MyConfig;
import com.cvmars.jianyou.config.UserOp;
import com.cvmars.jianyou.model.UserCoustomModel;
import com.cvmars.jianyou.model.UserModel;
import com.cvmars.jianyou.module.activity.HomeActivity;
import com.cvmars.jianyou.module.activity.NearByFriendActivity;
import com.cvmars.jianyou.module.activity.PersonHomeActivity;
import com.cvmars.jianyou.module.activity.XiangQingDaTingActivity;
import com.cvmars.jianyou.module.base.BaseFragment;
import com.cvmars.jianyou.module.model.AppConfigModel;
import com.cvmars.jianyou.utils.DeviceHelper;
import com.cvmars.jianyou.utils.ImageUtils;
import com.cvmars.jianyou.utils.ToastUtils;
import com.cvmars.jianyou.widget.card.CardConfig;
import com.cvmars.jianyou.widget.card.CardItemTouchHelperCallback;
import com.cvmars.jianyou.widget.card.CardLayoutManager;
import com.cvmars.jianyou.widget.card.OnSwipeListener;
import com.orhanobut.hawk.Hawk;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by hehaifeng on 2018/12/1.
 */

public class ChatFragment extends BaseFragment {


    @BindView(R.id.loading_base)
    AVLoadingIndicatorView loadingBase;
    @BindView(R.id.ll_nearby)
    TextView llNearby;
    @BindView(R.id.iv_xiangqing)
    ImageView ivXiangqing;
    @BindView(R.id.rl_empty)
    RelativeLayout rlEmpty;
    @BindView(R.id.ll_online)
    TextView llOnline;

    private List<UserModel> list = new ArrayList<>();
    RecyclerView recyclerView;
    Unbinder unbinder;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.frag_chat, null);
        initView(view);
        unbinder =
                ButterKnife.bind(this, view);
        requestData();
        getAppConfig();
        return view;
    }

    void startAnim() {
        loadingBase.show();  //显示
        // or avi.smoothToShow();
    }

    void stopAnim() {
        loadingBase.hide();   //隐藏
        // or avi.smoothToHide();
    }


    private void initView(View view) {
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(new MyAdapter());
        CardItemTouchHelperCallback cardCallback = new CardItemTouchHelperCallback(recyclerView.getAdapter(), list);
        cardCallback.setOnSwipedListener(new OnSwipeListener<UserModel>() {

            @Override
            public void onSwiping(RecyclerView.ViewHolder viewHolder, float ratio, int direction) {
                MyAdapter.MyViewHolder myHolder = (MyAdapter.MyViewHolder) viewHolder;
                viewHolder.itemView.setAlpha(1 - Math.abs(ratio) * 0.2f);

            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, UserModel o, int direction) {
                final MyAdapter.MyViewHolder myHolder = (MyAdapter.MyViewHolder) viewHolder;
                viewHolder.itemView.setAlpha(1f);

                if (direction == CardConfig.SWIPED_RIGHT) {

                    UserOp.onFollowing(o.id, "1", null);

                    int number = Hawk.get(MyConfig.SP_CACHE_NUM, 3);

                    if (number == 3) {

                        ToastUtils.show("右滑关注用户");
                    } else if (number == 2) {

                        ToastUtils.show("互相关注，开启聊天");

                    } else if (number == 1) {

                        ToastUtils.show("关注成功");
                    } else if (number == 0) {

                        ToastUtils.show("互相关注，开启聊天");
                    }
                    number--;
                    Hawk.put(MyConfig.SP_CACHE_NUM, number);
                }
            }

            @Override
            public void onSwipedClear() {
//                Toast.makeText(getActivity(), "data clear", Toast.LENGTH_SHORT).show();
                startAnim();
                mCurPage++;
                requestData();
            }


        });
        final ItemTouchHelper touchHelper = new ItemTouchHelper(cardCallback);
        final CardLayoutManager cardLayoutManager = new CardLayoutManager(recyclerView, touchHelper);
        recyclerView.setLayoutManager(cardLayoutManager);
        touchHelper.attachToRecyclerView(recyclerView);
    }


    private void initData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.ll_nearby, R.id.iv_xiangqing})
    public void onViewClicked(View view) {

        switch (view.getId()) {

            case R.id.ll_nearby:
                Intent intent = new Intent(getActivity(), NearByFriendActivity.class);
                startActivity(intent);
                break;

            case R.id.iv_xiangqing:
                Intent intentX = new Intent(getActivity(), XiangQingDaTingActivity.class);
                startActivity(intentX);
                break;


        }

    }

    @OnClick()
    public void onViewClicked() {
    }

    private class MyAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_card, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            final ImageView avatarImageView = ((MyViewHolder) holder).avatarImageView;
//            avatarImageView.setImageResource(list.get(position));

            final UserModel userModel = list.get(position);
            ImageUtils.loadImage(getActivity(), userModel.avatar_url, avatarImageView);
            MyViewHolder mHolder = (MyViewHolder) holder;
            mHolder.tv_name.setText(userModel.name);
            mHolder.txtAge.setText(userModel.age);
            mHolder.tv_constellation.setText(userModel.address_home);
            mHolder.txt_address.setText(!TextUtils.isEmpty(userModel.intro) ? userModel.intro : userModel.address_company);
            mHolder.love.setVisibility(userModel.is_rut ? View.VISIBLE : View.GONE);
            mHolder.rl_info.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    onGoHome(avatarImageView, userModel.id);
                }
            });

            mHolder.ivsex.setImageResource(userModel.gender == 1 ? R.drawable.ic_male : R.drawable.ic_women);

        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            ImageView avatarImageView;
            ImageView ivsex;
            ImageView love;


            View itemView;

            RelativeLayout rl_info;

            TextView txtAge, tv_name, tv_constellation, txt_address;
            CardView cardView;

            MyViewHolder(View itemView) {
                super(itemView);
                this.itemView = itemView;
                avatarImageView = (ImageView) itemView.findViewById(R.id.iv_avatar);
                cardView = (CardView) itemView.findViewById(R.id.card);
                txtAge = itemView.findViewById(R.id.tv_age);
                love = itemView.findViewById(R.id.iv_vip);
                rl_info = itemView.findViewById(R.id.rl_info);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_constellation = itemView.findViewById(R.id.tv_constellation);
                txt_address = itemView.findViewById(R.id.txt_address);
                ivsex = itemView.findViewById(R.id.iv_sex);
            }

        }
    }


    int mCurPage = 1;

    public void requestData() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getHomeList(mCurPage)
                , new SimpleSubscriber<HttpResult<UserCoustomModel>>() {
                    @Override
                    protected void _onNext(HttpResult<UserCoustomModel> o) {


                        UserCoustomModel data = o.getData();
                        if (data != null) {
                            List<UserModel> results = data.results;
                            list.addAll(results);
                            if (data.next == null) {

                                rlEmpty.setVisibility(View.VISIBLE);
                            }
                            recyclerView.getAdapter().notifyDataSetChanged();
                            stopAnim();
                        }

                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }


    private void getAppConfig() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getAppConfig()
                , new SimpleSubscriber<HttpResult<AppConfigModel>>() {
                    @Override
                    protected void _onNext(HttpResult<AppConfigModel> o) {

                        final AppConfigModel data = o.getData();
                        llOnline.setText(data.user_total);
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    private void onGoHome(View view, String id) {


        ActivityOptions options = null;

        Intent intent = new Intent(getActivity(),
                PersonHomeActivity.class);
        intent.putExtra("userid", id);

        startActivity(intent);

    }
}
